package testJdk.nio.testPipe;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.nio.charset.Charset;

/**
 * @author cyd
 * @version 1.0.0
 * @date 2021/11/27 16:35
 */


public class PipeDemo {

    public static void main(String[] args) throws IOException {
        // 1.获取管道
        Pipe pipe = Pipe.open();
        // 2.获取sink通道
        Pipe.SinkChannel sink = pipe.sink();
        // 3.创建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(48);
        byteBuffer.put("hello".getBytes());
        byteBuffer.flip();
        // 4.写入数据，对buffer来说是读取
        sink.write(byteBuffer);

        // 5.获取source通道
        Pipe.SourceChannel source = pipe.source();

        // 6.创建缓冲区，读取数据
        ByteBuffer byteBuffer02 = ByteBuffer.allocate(48);
        source.read(byteBuffer02);
        byteBuffer02.flip();
        System.out.println(Charset.forName("UTF-8").decode(byteBuffer02));
        // 7.关闭通道
        source.close();
        sink.close();
    }
}
